package com.zhsj.OkeHomeConsumption.ui.activity.citypartner;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.MenuDialog;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.CityPartnerShopBean;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.empty.MerchantTypeBean;
import com.zhsj.OkeHomeConsumption.ui.activity.WebActivity;
import com.zhsj.OkeHomeConsumption.ui.activity.citypartner.mvp.MerchantsWeihuRecruitPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.citypartner.mvp.MerchantsWeihuRecruitUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.entering.ShowSignCompactsFragment;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.zhsj.OkeHomeConsumption.utils.Utils.isFastDoubleClick;

/**
 * 商家维护
 */
public class MerchantsWeihuRecruitActivity extends MyActivity implements MerchantsWeihuRecruitUIInterFace {

    @BindView(R.id.finish)
    ImageView finish;

    @BindView(R.id.tl_recruit)
    TextView tlRecruit;//title

    @BindView(R.id.add)
    ImageView add;

    //招募对象
    @BindView(R.id.zhaomuduixiang_lin)
    LinearLayout zhaomuduixiang_lin;

    //入驻理由
    @BindView(R.id.grounds_lin)
    LinearLayout groundsLin;

    //入驻条件
    @BindView(R.id.ruzhutiaojian)
    LinearLayout ruzhutiaojian;


    //招募流程
    @BindView(R.id.zhaomuliucheng_lin)
    LinearLayout zhaomuliucheng_lin;
    @BindView(R.id.tool)
    Toolbar tool;

    @BindView(R.id.fenlei_text)
    TextView fenleiText;

    @BindView(R.id.lin1)
    RelativeLayout lin1;
    private RecyclerView recy;

    private SmartRefreshLayout refreshLayout;

    private MerchantsWeihuRecruitPresenter minePersonPresenter;

    private SharedPreferanceUtils mshared = null;

    private int pageIndex = 1;

    private List<CityPartnerShopBean> mCityPartnerShopList = null;

    private SQueryByCityAdapter mSQueryByCityAdapter = null;

    private FormalUserInfo userInfo;
    private String shopMobile;

    private ArrayList<MerchantTypeBean> mMerchantTypeLists = null;
    private List<CityPartnerShopBean> mRefushCityPartnerShopList = null;
    private String yijifenlei_id = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_merchants_weihurecruit;
    }

    @Override
    protected int getTitleId() {
        return 0;
    }

    @Override
    protected void initView() {
        mRefushCityPartnerShopList = new ArrayList<>();
        recy = findViewById(R.id.recyview);
        refreshLayout = findViewById(R.id.refreshLayout);
        mshared = new SharedPreferanceUtils(this);
        minePersonPresenter = new MerchantsWeihuRecruitPresenter(getActivity(), this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recy.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);

        //设置 Header 为 贝塞尔雷达 样式
        refreshLayout.setRefreshHeader(new BezierRadarHeader(this).setEnableHorizontalDrag(true));

    }

    @Override
    protected void initData() {
        tlRecruit.setText("商家维护");
        userInfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        minePersonPresenter.QueryByCityCoptnerGet(userInfo.getId(), 1,yijifenlei_id);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(2000);//传入false表示刷新失败
//                if (orderBeanList != null && orderBeanList.size() > 0) {
//                    orderBeanList.clear();
//                }
//                refreshLayout.setRefreshing(false);
                initRefersh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                NextPost();
            }
        });

    }

    public void initRefersh() {
        minePersonPresenter.QueryByCityCoptnerGet(userInfo.getId(), 1,yijifenlei_id);
    }

    public void NextPost() {
        pageIndex++;
        minePersonPresenter.QueryByCityCoptnerGet(userInfo.getId(), pageIndex,yijifenlei_id);
    }

    @OnClick({R.id.finish, R.id.add, R.id.zhaomuduixiang_lin, R.id.zhaomuliucheng_lin, R.id.grounds_lin, R.id.ruzhutiaojian,R.id.lin1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish:
                finish();
                break;

            case R.id.add:
                startActivityForResult(new Intent(getActivity(), AddBusinessInformationActivity.class), 0);
                break;
            case R.id.zhaomuduixiang_lin:
                Intent intent = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/7.html");
                startActivity(intent);
                break;
            case R.id.grounds_lin:
                Intent intent2 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/14.html");
                startActivity(intent2);
                break;
            case R.id.ruzhutiaojian:
                Intent intent3 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/8.html");
                startActivity(intent3);
                break;
            case R.id.zhaomuliucheng_lin:
                Intent intent4 = new Intent(getActivity(), WebActivity.class).putExtra("url", OkeHomeConsumptionApi.ELVDOU_BASEURL_H5_LIFE + "app/h5/platform/6.html");
                startActivity(intent4);
                break;
            case R.id.lin1:
                minePersonPresenter.MerchantTypeGet();
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }


    /**
     * 获取邀请的店铺列表
     */
    @Override
    public void QueryByCityCoptnerGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mCityPartnerShopList = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<CityPartnerShopBean>>() {
                        }.getType());
                mRefushCityPartnerShopList.addAll(mCityPartnerShopList);
                if(pageIndex!=1){
                    if(mCityPartnerShopList.size()!=0){
                        mSQueryByCityAdapter.addData(mCityPartnerShopList);
                    }else{
                        //完成加载并标记没有更多数据
                        toast("没有更多数据");
                        refreshLayout.finishLoadMoreWithNoMoreData();
                        return;

                    }
                }
                mSQueryByCityAdapter = new SQueryByCityAdapter();
                recy.setAdapter(mSQueryByCityAdapter);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("MerchantChildTypeGet", "获取邀请的店铺列表");
        }
    }

    @Override
    public void ContractPreViewGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                String data = jsonOBJ.optString("data");
                startActivityForResult(new Intent(this, ShowSignCompactsFragment.class).putExtra("web_url", data).putExtra("type", 2), 0);
                if (isFastDoubleClick()) {
                    return;
                }
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                }
            } else {
                if (!message.equals("null")) {
                }
            }
        } catch (JSONException ex) {
            LogUtils.e("预览电子合同", ex.toString());
        }
    }


    public class SQueryByCityAdapter extends BaseQuickAdapter<CityPartnerShopBean, BaseViewHolder> {
        public SQueryByCityAdapter() {
            super(R.layout.item_merchants_fragment, mRefushCityPartnerShopList);
        }

        @Override
        protected void convert(BaseViewHolder helper, final CityPartnerShopBean item) {
            helper.setText(R.id.type_text, "待沟通")//点过跟踪按钮或打电话按钮就变为以沟通
                    .setText(R.id.data, item.getCreateTime())
                    .setText(R.id.name, item.getShopName())
                    .setText(R.id.area, item.getDistricCountryName())
                    .setText(R.id.phone, item.getShopMobile())
                    .setText(R.id.path, item.getAddress())
                    .setText(R.id.location, item.getCategoryText())
                    .setOnClickListener(R.id.xiangqing_text, new AdapterView.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //查看详情
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("CityPartnerShop", item);
                            startActivity(new Intent(getActivity(),StoredetailsActivity.class).putExtras(bundle).putExtra("flag","1"));
                        }

                    }).setOnClickListener(R.id.lookxieyi_text, new AdapterView.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //查看协议
                    minePersonPresenter.ContractPreViewGet("1",String.valueOf(item.getUserId()));
                }
            }).setOnClickListener(R.id.wanshan_text, new AdapterView.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //完善信息
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("CityPartnerShop", item);
                    startActivity(new Intent(getActivity(),StoredetailsActivity.class).putExtras(bundle).putExtra("flag","2"));
                }
            }).setOnClickListener(R.id.dadianhua_text, new AdapterView.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //打电话
                    XXPermissions.with(getActivity())
                            .permission(Permission.CALL_PHONE) //不指定权限则自动获取清单中的危险权限
                            .request(new OnPermission() {

                                @Override
                                public void hasPermission(List<String> granted, boolean isAll) {
                                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + item.getShopMobile()));
                                    startActivity(intent);
                                }

                                @Override
                                public void noPermission(List<String> denied, boolean quick) {
                                }
                            });

                }
            });
        }
    }
    @Override
    public void MerchantTypeGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mMerchantTypeLists = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<MerchantTypeBean>>() {
                        }.getType());
                List<String> datalist = new ArrayList<>();
                for (int i = 0; i < mMerchantTypeLists.size(); i++) {
                    datalist.add(mMerchantTypeLists.get(i).getName());
                }
                MenuDialog(datalist);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("MerchantTypeGet", "获取经营类型异常");
        }
    }

    private void MenuDialog(final List<String> datalist){
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(datalist)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        fenleiText.setText(datalist.get(position));
                        yijifenlei_id =String.valueOf(mMerchantTypeLists.get(position).getId());
                        minePersonPresenter.QueryByCityCoptnerGet(userInfo.getId(), 1,yijifenlei_id);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }
}
